package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.SystemMenu;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Iterator;
import java.util.List;

public class SystemMenuUtil {

    public static final String SYSTEM_MENU_IN_SESSION = "system_menu_in_session";


    //递归过滤菜单
    private static void fitlerSystemMenu(List<SystemMenu> menus){
        //获取当前用户所有的权限
        Subject subject = SecurityUtils.getSubject();

        //遍历menus集合, 判断menus菜单对应的权限是否在用户权限集合中
        //使用迭代器遍历原因: 增强循环无法删除集合元素
        Iterator<SystemMenu> iter = menus.iterator();
        while(iter.hasNext()){
            SystemMenu menu = iter.next();
            //获取菜单绑定权限
            Permission permission = menu.getPermission();
            if(permission != null){
                //判断当前登录的用户是否拥有此权限
                if(!subject.isPermitted(permission.getResource())){
                    iter.remove(); //删除
                }
            }
            //如果有儿子, 也需要进行迭代判断
            List<SystemMenu> children = menu.getChildren();
            if(children != null && children.size() > 0){
                //递归过滤儿子的儿子的子菜单
                fitlerSystemMenu(children);
            }
        }
    }

    //优化, 删除过滤菜单之后存在无儿子的父菜单
    public static void filterMenu(List<SystemMenu> menus) {

        //过滤菜单
        fitlerSystemMenu(menus);

        //删除无儿子的父菜单(空菜单)
        Iterator<SystemMenu> iter = menus.iterator();
        while (iter.hasNext()){
            SystemMenu menu = iter.next();
            if(menu.getChildren() == null || menu.getChildren().size() == 0){
                iter.remove();
            }
        }
    }
}
